<?php



namespace App\Http\Requests\ApiV2;

use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class UserRedpacketRequest extends BaseRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'parts' => 'required|integer|min:1',
            'total' => 'required|min:1',
            'step' => 'required|integer|min:1',
        ];
    }

    public function messages()
    {
        return [
            'blessing_words.required' => __('请输入祝福语'),
            'parts.required' => __('请输入个数'),
            'total.required' => __('请输入总数'),
            'step.required' => __('请输入发送红包的步数'),


        ];
    }

    public function filldata()
    {

        $parts = (int)$this->input('parts');
        $total= $this->input('total');
        $mean = $total / $parts;
        $stddev = $mean / 3; // 设置标准差
        $partitions = [];

        // 生成每个分区，允许两位小数
        for ($i = 0; $i < $parts; $i++) {
            do {
                $partition = round(max(0.01, $mean + mt_rand_normal($mean, $stddev)), 2);
            } while ($partition < 0.01);
            $partitions[] = $partition;
        }

        // 调整总数
        $currentTotal = array_sum($partitions);
        $diff = round($total - $currentTotal, 2);

        // 对于调整差额，分布到各个分区
        for ($i = 0; $i < $parts; $i++) {
            $partitions[$i] = round($partitions[$i] + $diff / $parts, 2);
        }

        // 处理可能的小数误差，确保总和等于 total
        $currentTotal = array_sum($partitions);
        $finalDiff = round($total - $currentTotal, 2);
        if (abs($finalDiff) > 0.01) {
            $partitions[0] = round($partitions[0] + $finalDiff, 2); // 对第一个分区进行微调
        }
        $user = Auth::user();
        return [
            'user_id'=>(int)$user['id'],
            'receiver_id'=>(int)$this->input('receiver_id'),
            'blessing_words' =>(string) $this->input('blessing_words'),
            'step' =>(int) $this->input('step'),
            'parts'=>$parts,
            'total'=>$total,
            'reward_value'=>implode('|',$partitions)
        ];
    }
}
